﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KZ400B.AxleSettings;

namespace KZ400B.Controls
{
    public delegate void StateChange(AxleAction action,string state);
    /// <summary>
    /// AxleState.xaml 的交互逻辑
    /// </summary>
    public partial class AxleState : UserControl
    {
        public AxleState()
        {
            InitializeComponent();
            
            this.Loaded += new RoutedEventHandler(AxleState_Loaded);
            this.Unloaded += new RoutedEventHandler(AxleState_Unloaded);
            AxleManager.OnAxleActionResponse += new AxleActionResponse(AxleManager_OnAxleActionResponse);

        }

        void AxleState_Unloaded(object sender, RoutedEventArgs e)
        {
            AxleManager.OnAxleActionResponse -= new AxleActionResponse(AxleManager_OnAxleActionResponse);
        }

        void AxleManager_OnAxleActionResponse(string axleName
            , Axle axle
            , AxleActions action
            , bool success
            , string message)
        {
            if (action == AxleActions.Contact && success)
            {
                AxleManager.QueryPosition(AxleName);
                int aLevel = 0;
                if (cmbAcceleration.SelectedValue != null && int.TryParse(cmbAcceleration.SelectedValue.ToString(), out aLevel))
                {
                    if (aLevel != Axle.AccelerationLevel.Constant)
                    {
                        Axle.AccelerationLevel acc = new Axle.AccelerationLevel(aLevel);
                        if (AxleManager.AccelerationSetting(AxleName, acc))
                        {
                            setState(
                            string.Format("加速度({0}|[{1}])设置成功"
                                , AxleName, acc.ToString()
                                )
                            );
                        }
                        else
                        {
                            setState(
                            string.Format("加速度({0}|[{1}])设置失败"
                                , AxleName, acc.ToString()
                                )
                            );
                        }
                    }
                }
            }
            else if (action == AxleActions.ToZeroFinish && success )
            {
                if (axleName.Equals(m_Axle.Name) || axleName.Equals(Axle.AllAxleName))
                {
                    OnToZeroSucceed();
                }
            }
            /*
            else if (action == AxleActions.ToZero
                || action == AxleActions.Stop
                || action == AxleActions.Run
                )
            {
                if (axleName.Equals(AxleName) 
                    || AxleName.Equals(Axle.AllAxleName)
                    )
                {
                    AxleManager.QueryPosition(AxleName);
                }

            }
             */
        }

        public event StateChange OnStateChanged;


        void AxleState_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(AxleName))
            {
                throw new Exception("AxleName 不能为空");
            }
            m_Axle = AxleCacheManager.getAxle(AxleName);
            
            grpAxle.Header = string.Format("{0}轴",AxleName);
            if (m_Axle == null)
                return;
            //AxlePosition = (double)( m_Axle.Position );
            m_orgPosition = m_Axle.Position;
            m_lastPosition = m_Axle.Position;
            m_lastUnit = m_Axle.RunningUnit;
            labAxlePostion.Content = m_Axle.Position.ToString(MySetting.PositionDisDeciFormatter);

            #region bind
            addtionDirectBind(
                m_Axle.OnestepAddtion >= 0 
                ? Axle.Direction.ForwardDirection.Value 
                : Axle.Direction.BackDirection.Value
                );
            addtionBind(Math.Abs(m_Axle.OnestepAddtion));
            targetBind(m_Axle.RunTarget);
            accelerationBind(m_Axle.RunAcceleration);
            tozeroSpeedBind();

            AxlePositionUnit = (int)m_Axle.RunningUnit;
            #endregion 
            //if (m_Axle.OnestepAddtion == 0)
            //{
            //    cmbAddtionDirect.SelectedValue = (int)Axle.Direction.ForwardDirection.Value;
            //    cmbAddtion.SelectedValue = m_Axle.OnestepAddtion;
            //}
            //else
            //{
            //    cmbAddtionDirect.SelectedValue = (int)Axle.Direction.BackDirection.Value;
            //    cmbAddtion.SelectedValue = 0 - m_Axle.OnestepAddtion;
            //}
            txtSpeed.Text = m_Axle.RunSpeed.ToString();
            txtTozeroSpeed.Text = m_Axle.TozeroSpeed.ToString();
            changeParam();
            AxleManager.setParameterChanged(AxleName, true);

            setState(string.Format("加载完成"));
        }

        public static DependencyProperty AxleNameProperty = DependencyProperty.Register(
        "AxleName", typeof(string)
        , typeof(AxleState)
        , new PropertyMetadata(string.Empty)
    );

        public void RefreshDisplay()
        {
            labAxlePostion.Content = m_lastPosition.ToString(MySetting.PositionDisDeciFormatter);
        }

        public string AxleName
        {
            get { return (string)GetValue(AxleNameProperty); }
            set { SetValue(AxleNameProperty, value); }
        }

        private Axle m_Axle;
        //private RunningUnit m_rUnit;

        /// <summary>
        /// 相对零位设置
        /// </summary>
        public static DependencyProperty AxleRelativeZeroProperty = DependencyProperty.Register(
            "AxleRelativeZero", typeof(double)
            , typeof(AxleState)
             , new PropertyMetadata((double)0.0F, new PropertyChangedCallback(OnAxleRelativeZeroChange))
            );

        public double AxleRelativeZero
        {
            get { return (double)GetValue(AxleRelativeZeroProperty); }
            set { SetValue(AxleRelativeZeroProperty, value); }
        }

        private static void OnAxleRelativeZeroChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AxleState control = (AxleState)d;
            //if ((int)(control.AxlePosition) == 0)
            //{ control.labAxlePostion.Content = "0.000"; }
            //else
            //{ control.labAxlePostion.Content = control.AxlePosition.ToString("0.000"); }
            control.m_Axle.RelativeZero = control.AxleRelativeZero;
            AxleCacheManager.Update(control.m_Axle);
        }

        
        public static DependencyProperty AxlePositionProperty = DependencyProperty.Register(
            "AxlePosition",typeof(double)
            , typeof(AxleState)
             , new PropertyMetadata(Axle.DefaultPosition, new PropertyChangedCallback(OnPositionChange))
            );

        public double AxlePosition
        {
            get { return (double)GetValue(AxlePositionProperty); }
            set { SetValue(AxlePositionProperty, value); }
        }

        private static void OnPositionChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AxleState control = (AxleState)d;
            //if ((int)(control.AxlePosition) == 0)
            //{ control.labAxlePostion.Content = "0.000"; }
            //else
            if (control.m_Axle != null)
            {
                double pos = Axle.ComputeRelativePosition(control.AxlePosition,control.m_Axle.RelativeZero);
                
                //double pos = control.computeRelativePosition(control.AxlePosition);
                //if (control.m_lastUnit == RunningUnits.Step)
                //{
                //    pos = pos / control.m_Axle.OnestepDisplacement;
                //}
                control.labAxlePostion.Content = pos.ToString(MySetting.PositionDisDeciFormatter);
                //{ control.labAxlePostion.Content = pos.ToString(MySetting.PositionDisDeciFormatter); }
                control.m_Axle.Position = pos;
                control.m_orgPosition = pos;
                control.m_lastPosition = pos;
                control.m_orgUnit = (RunningUnits)control.AxlePositionUnit;

                //AxleCacheManager.Update(control.m_Axle);
            }
        }

        bool m_isNeedChangeToStep = false;
        bool m_isNeedChangeToOtherUnit = false;
        double m_orgPosition = 0.0F;
        double m_lastPosition = 0.0F;
        RunningUnits m_orgUnit = RunningUnits.UnDefined;
        RunningUnits m_lastUnit = RunningUnits.UnDefined;

        //private double computeRelativePosition(double position)
        //{
        //    double ps = position;
        //    if (position >= 0)
        //    {
        //        if (m_Axle.RelativeZero > 0)
        //        {
        //            ps = position - m_Axle.RelativeZero;
        //        }
        //        else
        //        {
        //            ps = position + m_Axle.RelativeZero;
        //        }
        //    }
        //    else
        //    {
        //        if (m_Axle.RelativeZero > 0)
        //        {
        //            ps = position + m_Axle.RelativeZero;
        //        }
        //        else
        //        {
        //            ps = position - m_Axle.RelativeZero;
        //        }
        //    }
        //    return ps;
        //}

        /*
         //单位转换，显示要跟着相应转换
         */
        private double convertPositionByUnit(double position)
        {
            double ps = position;
            if (m_orgUnit == RunningUnits.Step)
            {
                if (m_isNeedChangeToOtherUnit)
                {
                    ps = position * m_Axle.OnestepDisplacement;
                }
            }
            else { 
                if (m_isNeedChangeToStep)
                {
                    int ips = Convert.ToInt32(position / m_Axle.OnestepDisplacement);
                    ps = (double)ips;
                }
            }
            return ps;
        }

        public static DependencyProperty AxlePositionUnitProperty = DependencyProperty.Register(
        "AxlePositionUnit", typeof(int)
        , typeof(AxleState)
         , new PropertyMetadata((int)RunningUnits.UnDefined, new PropertyChangedCallback(OnAxlePositionUnitChange))
        );

        public int AxlePositionUnit
        {
            get { return (int)GetValue(AxlePositionUnitProperty); }
            set { SetValue(AxlePositionUnitProperty, value); }
        }

        private static Dictionary<string, string> sdictUnits = new Dictionary<string, string>() 
        { 
            {"步数","step"},
            {"毫米","mm"},
            {"度数","deg"},
            {"STEP","step"},
            {"MILLIMETER","mm"},
            {"RADIAN","deg"},
            {"MM","mm"}
        };

       private static string getUnitNameByAltName(string unitAltName)
        {
            if (string.IsNullOrEmpty(unitAltName))
            {
                return string.Empty;
            }
            if (sdictUnits.ContainsKey(unitAltName))
            { 
                return sdictUnits[unitAltName];
            }
            else if (sdictUnits.ContainsKey(unitAltName.ToUpper()))
            {
                return sdictUnits[unitAltName.ToUpper()];
            }
            return string.Empty;
        }

        private static void OnAxlePositionUnitChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AxleState control = (AxleState)d;
            int intPu = control.AxlePositionUnit;
            RunningUnits pu = (RunningUnits)intPu;
            
            string name = RunningUnitCacheManager.getName(intPu);
            string altName = RunningUnitCacheManager.getAltName(intPu);
            string uName = getUnitNameByAltName(altName);

            control.labAxlePostionUnit.Content = altName;
            control.labAddtionUnit.Content = altName;
            control.labTargetUnit.Content = altName;

            control.labSpeedUnit.Content = uName;
            control.labTozeroSpeedUnit.Content = uName;

            if (control.m_lastUnit == RunningUnits.UnDefined)
            {
                control.m_isNeedChangeToOtherUnit = false;
                control.m_isNeedChangeToStep = false;
            }
            else if (
                control.m_lastUnit == RunningUnits.Step
                && control.m_lastUnit != pu
                )//从步数转换为其它单位
            {
                control.m_isNeedChangeToOtherUnit = true;
                control.m_isNeedChangeToStep = false;
            }
            else if(
                control.m_lastUnit != RunningUnits.Step 
                && pu == (int)RunningUnits.Step
                )//从其它单位转换为步数
            {
                control.m_isNeedChangeToOtherUnit = false;
                control.m_isNeedChangeToStep = true;
            }
            control.m_lastUnit = (RunningUnits)control.AxlePositionUnit;

            //转换显示位置
            if (control.m_Axle != null)
            {
                double npos = control.convertPositionByUnit(control.m_orgPosition);
                { control.labAxlePostion.Content = npos.ToString(MySetting.PositionDisDeciFormatter); }

                control.m_Axle.Position = npos;
                control.m_Axle.RunningUnit = pu;
                AxleCacheManager.Update(control.m_Axle);

                control.m_lastPosition = npos;
            }
            else
            {
                control.m_lastUnit = RunningUnits.UnDefined;
            }
        }

        private double computeAddtion(double target,ref int dir)
        {
            double nt = target;
            dir = Axle.Direction.ForwardDirection.Value;
            double rZero = m_Axle.RelativeZero;
            if (m_lastUnit == RunningUnits.Step)
            {
                rZero = rZero / m_Axle.OnestepDisplacement;
            }
            if ((nt + rZero) < 0)
            {
                //if (nt > (m_Axle.Position + m_Axle.RelativeZero))
                {
                    throw new Exception("运行目标超越绝对零位!");
                }
            }

            if (nt < m_Axle.Position)
            {
                if (nt < 0)
                {
                    nt = 0 - target;
                    //if (m_Axle.RelativeZero > 0)
                    //{
                    //    nt += m_Axle.RelativeZero;
                    //}
                    nt += m_Axle.Position;// +m_Axle.RelativeZero;
                    
                }
                else
                {
                    nt -= m_Axle.Position;
                }
                if (nt < 0)
                {
                    nt = 0 - nt;
                }
                dir = Axle.Direction.BackDirection.Value;
            }
            else
            {
                if (m_Axle.RelativeZero < 0)
                {
                    nt -= rZero;
                    throw new Exception("绝对零位不能小于0!");
                }
                nt -= m_Axle.Position;// +m_Axle.RelativeZero;
            }
            return nt;
        }

        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            int direct = Axle.Direction.ForwardDirection.Value;
            double totalStep = 0;
            try
            {
                if (double.TryParse(cmbTarget.SelectedItem.ToString(), out totalStep))
                {
                    totalStep = computeAddtion(totalStep,ref direct);
                    if (totalStep == 0.0F)
                    {
                        return;
                    }
                    //if (totalStep < 0)
                    //{
                    //    direct = Axle.Direction.BackDirection.Value;
                    //    totalStep = 0 - totalStep;
                    //}
                    m_Axle.Addtion = totalStep;

                    Axle.Direction dirt = new Axle.Direction(direct);
                    double pwm = m_Axle.getRunPwm(m_runSpeed);

                    bool setRst = AxleManager.ParameterSetting(AxleName
                        , dirt
                        , pwm
                        , m_Axle.TotalStep);
                    if (setRst)
                    {
                        setState(
                        string.Format("参数设置({0}|[{1}]|{2}|{3})成功"
                            , AxleName, dirt.ToString()
                            , pwm
                            , m_Axle.TotalStep
                            )
                        );
                        AxleCacheManager.Update(m_Axle);
                        AxleManager.Run(AxleName);
                    }
                    else
                    {
                        setState(
                            string.Format("参数设置({0}|[{1}]|{2}|{3})失败"
                                , AxleName, dirt.ToString()
                                , pwm
                                , m_Axle.TotalStep
                                )
                            );
                    }
                }
            }
            catch (Exception ex)
            {
                setState(
                                string.Format("参数设置错误:({0})"
                                    ,ex.Message
                                    )
                                );
            }
            
        }

        /// <summary>
        /// 设置相对零位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetRelativelyZero_Click(object sender, RoutedEventArgs e)
        {
            bool rst = AxleManager.RelativeZero(AxleName);
            AxleManager.setParameterChanged(AxleName, true);
            setState(
            string.Format("相对零位设置({0}|[{1}])"
                , AxleName
                , rst ? "成功" : "失败"
                )
            );
            if (rst)
            {
                try
                {
                    AxleManager.setParameterChanged(AxleName, true);
                    //m_Axle.RelativeZero = m_Axle.Position;
                    //AxleCacheManager.Update(m_Axle);
                    double pos = 0.0F;
                    rst = AxleManager.QueryOneAxlePosition(AxleName, ref pos);
                    if (rst)
                    {
                        m_Axle.RelativeZero = pos;
                        m_Axle.Position = Axle.ComputeRelativePosition(pos,pos);
                        AxleCacheManager.Update(m_Axle);
                        labAxlePostion.Dispatcher.BeginInvoke(new Action(delegate()
                            {
                                PositionCacheManager.ChangePosition(AxleName, pos, true);
                                labAxlePostion.Content = 0.ToString(MySetting.PositionDisDeciFormatter);
                                //labAxlePostion.Content = "0.000"; 
                            }));
                        
                    }
                }
                catch (Exception ex)
                {
                    setState(
                                    string.Format("参数设置错误:({0})"
                                        , ex.Message
                                        )
                                    );
                }
            }
            /*
            double oldZero = m_Axle.RelativeZero;
            double newZero = 0;
            double addtion = 0;
            if (cmbTarget.SelectedItem != null && double.TryParse(cmbTarget.SelectedItem.ToString(), out newZero))
            {
                Axle.Direction dirt = Axle.Direction.ForwardDirection;
                if (newZero > oldZero)
                {
                    addtion = newZero - oldZero;
                }
                if (newZero < oldZero)
                {
                    dirt = Axle.Direction.BackDirection;
                    addtion = oldZero - newZero;
                }
                if (addtion > 0)
                {
                    m_Axle.RelativeZero = newZero;
                    
                    m_Axle.Addtion = (int)addtion;
                    double pwm = m_Axle.getRunPwm(m_runSpeed);
                    bool rst = AxleManager.ParameterSetting(
                        AxleName
                        , dirt
                        , pwm
                        , m_Axle.TotalStep);

                    setState(
                        string.Format("参数设置({0}|[{1}]|{2}|{3}){4}"
                            , AxleName, dirt.ToString()
                            , pwm
                            , m_Axle.TotalStep
                            ,rst ? "成功" : "失败"
                            )
                        );

                    if (rst)
                    {
                        AxleCacheManager.Update(m_Axle);
                        rst = AxleManager.RelativeZero(AxleName);
                        setState(
                        string.Format("相对零位设置({0}|[{1}])"
                            , AxleName
                            , rst ? "成功" : "失败"
                            )
                        );
                        if (rst)
                        {
                            AxleManager.QueryPosition(AxleName);
                        }
                    }
                }
            }*/
            
        }

        /// <summary>
        /// 归零
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTozero_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                AxleManager.ToZero(AxleName, m_Axle.getTozeroPwm(m_tozeroSpeed));
                AxleManager.setParameterChanged(AxleName, true);
            }
            catch (Exception ex)
            {
                setState(
                                string.Format("参数设置错误:({0})"
                                    , ex.Message
                                    )
                                );
            }
        }

        /// <summary>
        /// 归零成功后需要调用
        /// </summary>
        public void OnToZeroSucceed()
        {
            m_Axle.RelativeZero = 0;
            m_Axle.Position = 0;
            labAxlePostion.Dispatcher.BeginInvoke(new Action(delegate()
            { 
                //labAxlePostion.Content = "0.000"; 
                //AxlePosition = 0;
                PositionCacheManager.ChangePosition(AxleName, 0, true);
                labAxlePostion.Content = 0.ToString(MySetting.PositionDisDeciFormatter);
            }));
            AxleCacheManager.Update(m_Axle);
        }


        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                AxleManager.Stop(AxleName);
            }
            catch (Exception ex)
            {
                setState(
                                string.Format("参数设置错误:({0})"
                                    , ex.Message
                                    )
                                );
            }
        }

        //private void btnDown_Click(object sender, RoutedEventArgs e)
        //{

        //}

        //private void btnUp_Click(object sender, RoutedEventArgs e)
        //{

        //}

        /// <summary>
        /// 单步增量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOneStepAddtion_Click(object sender, RoutedEventArgs e)
        {
            int direct = 0;
            int totalStep = 0;
            try
            {
                if (int.TryParse(cmbAddtionDirect.SelectedValue.ToString(), out direct))
                {
                    if (int.TryParse(cmbAddtion.SelectedItem.ToString(), out totalStep))
                    {
                        m_Axle.Addtion = totalStep;
                        Axle.Direction dirt = new Axle.Direction(direct);
                        double pwm = m_Axle.getRunPwm(m_runSpeed);
                        bool setRst = AxleManager.ParameterSetting(AxleName
                            , new Axle.Direction(direct)
                            , m_Axle.getRunPwm(m_runSpeed)
                            , m_Axle.TotalStep
                            );
                        m_Axle.OnestepAddtion = direct == 0 ? totalStep : (0 - totalStep);
                        if (setRst)
                        {
                            setState(
                            string.Format("参数设置({0}|[{1}]|{2}|{3})成功"
                                , AxleName, dirt.ToString()
                                , pwm
                                , m_Axle.TotalStep
                                )
                            );
                            AxleCacheManager.Update(m_Axle);
                            AxleManager.Run(AxleName);
                        }
                        else
                        {
                            setState(
                            string.Format("参数设置({0}|[{1}]|{2}|{3})失败"
                                , AxleName, dirt.ToString()
                                , pwm
                                , m_Axle.TotalStep
                                )
                            );
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                setState(
                                string.Format("参数设置错误:({0})"
                                    , ex.Message
                                    )
                                );
            }
        }

        #region bind
        /// <summary>
        /// 方向
        /// </summary>
        private static List<AddtionDirect> s_addDirectTypeList = new List<AddtionDirect>()
                {
                new AddtionDirect((int)Axle.Direction.ForwardDirection.Value,"+"),
                new AddtionDirect((int)Axle.Direction.BackDirection.Value,"-")
                };
        private static List<AccelerationSetting> s_accelerationList = new List<AccelerationSetting>()
        {
            new AccelerationSetting((int)Axle.AccelerationLevel.Constant,"匀速"),
            new AccelerationSetting((int)Axle.AccelerationLevel.GatherWay,"加速")
        };

        private static List<ToZeroSpeedSetting> s_tozeroSpeedList = new List<ToZeroSpeedSetting>()
        {
            new ToZeroSpeedSetting((int)Axle.ToZeroSpeed.Constant,"匀速"),
            new ToZeroSpeedSetting((int)Axle.ToZeroSpeed.GatherWay,"加速")
        };

        void accelerationBind(int value)
        {
            cmbAcceleration.ItemsSource = s_accelerationList;
            cmbAcceleration.DisplayMemberPath = "Name";
            cmbAcceleration.SelectedValuePath = "ID";
            if (value > 0)
            {
                cmbAcceleration.SelectedValue = value;
            }
            else
            {
                cmbAcceleration.SelectedIndex = 0;
            }
        }

        void tozeroSpeedBind()
        {
            //cmbTozeroSpeed.ItemsSource = s_tozeroSpeedList;
            //cmbTozeroSpeed.DisplayMemberPath = "Name";
            //cmbTozeroSpeed.SelectedValuePath = "ID";
            //cmbTozeroSpeed.SelectedIndex = 0;
        }

        void addtionDirectBind(int value)
        {
            cmbAddtionDirect.ItemsSource = s_addDirectTypeList;
            cmbAddtionDirect.DisplayMemberPath = "Name";
            cmbAddtionDirect.SelectedValuePath = "ID";
            if (value > 0)
            {
                cmbAddtionDirect.SelectedValue = value;
            }
            else
            {
                cmbAddtionDirect.SelectedIndex = 0;
            }
        }

        void addtionBind(int value)
        {
            List<int> mList = new List<int>();
            for (int i = 1; i < 101; i++)
            {
                mList.Add(i);
            }

            cmbAddtion.ItemsSource = mList;
            if (value > 0)
            {
                cmbAddtion.SelectedValue = value;
            }
            else
            {
                cmbAddtion.SelectedIndex = 0;
            }
        }

        void targetBind(double target)
        {
            List<double> mList = new List<double>();
            for (int i = 1; i < 101; i++)
            {
                mList.Add((double)i);
            }

            cmbTarget.ItemsSource = mList;
            //if (target >= 0)
            { cmbTarget.BindValue(target); }
            //else
            //{
            //    cmbTarget.SelectedIndex = 0;
            //}
            
        }
        #endregion

        #region 变化事件
        private void cmbAddtion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int aValue = 0;
            int bValue = 0;
            if (cmbAddtion.SelectedValue != null && int.TryParse(cmbAddtion.SelectedValue.ToString(), out aValue))
            {
                if (cmbAddtionDirect.SelectedValue != null && int.TryParse(cmbAddtionDirect.SelectedValue.ToString(), out bValue))
                {
                    m_Axle.OnestepAddtion = bValue == 0 ? aValue : 0 - aValue ;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
            }
        }

        private void cmbAddtionDirect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int aValue = 0;
            int bValue = 0;
            if (cmbAddtion.SelectedValue != null && int.TryParse(cmbAddtion.SelectedValue.ToString(), out aValue))
            {
                if (cmbAddtionDirect.SelectedValue != null && int.TryParse(cmbAddtionDirect.SelectedValue.ToString(), out bValue))
                {
                    m_Axle.OnestepAddtion = bValue == 0 ? aValue : 0 - aValue;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
            }
        }

        private void cmbAcceleration_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int aLevel = 0;
            if (cmbAcceleration.SelectedValue != null && int.TryParse(cmbAcceleration.SelectedValue.ToString(), out aLevel))
            {
                Axle.AccelerationLevel acc = new Axle.AccelerationLevel(aLevel);
                if (AxleManager.AccelerationSetting(AxleName, acc))
                {
                    setState(
                    string.Format("加速度({0}|[{1}])设置成功"
                        , AxleName, acc.ToString()
                        )
                    );
                    m_Axle.RunAcceleration = aLevel;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
                else
                {
                    setState(
                    string.Format("加速度({0}|[{1}])设置失败"
                        , AxleName,acc.ToString()
                        )
                    );
                    cmbAcceleration.SelectedValue = m_Axle.RunAcceleration;
                }
            }
        }

        private double m_runSpeed = 0.0F;

        public double RunSpeed
        {
            get { return m_runSpeed; }
        }
        private double m_tozeroSpeed = 0.0F;

        public double TozeroSpeed
        {
            get { return m_tozeroSpeed; }
        }
        private void txtTozeroSpeed_TextChanged(object sender, TextChangedEventArgs e)
        {
            double dValue = 0.0F;
            if (double.TryParse(txtTozeroSpeed.Text, out dValue))
            {
                if (m_Axle.TozeroSpeed != dValue)
                {
                    m_Axle.TozeroSpeed = dValue;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
            }
            m_tozeroSpeed = dValue;
        }

        private void txtSpeed_TextChanged(object sender, TextChangedEventArgs e)
        {
            double dValue = 0.0F;
            if (double.TryParse(txtSpeed.Text, out dValue))
            {
                if (m_Axle.RunSpeed != dValue)
                {
                    m_Axle.RunSpeed = dValue;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
            }
            m_runSpeed = dValue;
        }

        private void cmbTarget_DataChanged(object sender)
        {
            double dValue = 0;
            if (cmbTarget.SelectedItem != null && double.TryParse(cmbTarget.SelectedItem.ToString(), out dValue))
            {
                if (!m_Axle.RunTarget.ToString(MySetting.PositionDisDeciFormatter).Equals(dValue.ToString(MySetting.PositionDisDeciFormatter)))
                {
                    m_Axle.RunTarget = dValue;
                    AxleCacheManager.Update(m_Axle);
                    changeParam();
                }
            }
        }

        #endregion

        private bool m_paramChanged;
        private void resetPState()
        { 
        
        }
        /// <summary>
        /// 参数修改时调用
        /// </summary>
        private void changeParam()
        {
            AxleManager.setParameterChanged(AxleName, true);
        //update to database
        }

        private void setRunning(bool running)
        { 
            
        }

        /// <summary>
        /// 判断电机是否正在运转
        /// </summary>
        /// <returns></returns>
        private bool isRunning()
        {
            return false;
        }

        /// <summary>
        /// 设置控件是否可用
        /// 如果正在运行应该设置其它控件为不可用
        /// 运行结束或者没有运行时为可用
        /// </summary>
        /// <param name="enable"></param>
        private void setEnable(bool enable)
        { 
            
        }



        private void setState(string state)
        {
            if (OnStateChanged != null && !string.IsNullOrEmpty(state))
            {
                OnStateChanged(null,state);
            }
        }


    }
}
